//
//  SMLoginView.swift
//  SomePasti
//
//  Created by 李永彬 on 2025/10/15.
//

import SwiftUI

struct SMLoginView: View {
    @EnvironmentObject private var appState: SMAppState
    @State private var phoneNumber: String = ""
    @State private var password: String = ""
    @State private var isCountdown = false
    @State private var countdownSeconds = 60
    @State private var countdownTimer: Timer?
    
    @Environment(\.presentationMode) var presentationMode
    
    // 判断是否是 present 过来的
    var isPresented: Bool {
        presentationMode.wrappedValue.isPresented
    }
    
    var body: some View {
        VStack {
            Group {
                Spacer()
                    .frame(height: 280)
                
                Text("No need to wait, instant loan")
                    .frame(maxWidth: .infinity, alignment: .leading)
                    .foregroundColor(Color.black)
                
                HStack {
                    Text("+92")
                        .foregroundColor(Color.black)
                        .padding(.leading, 5)
                    
                    TextField("Please enter the number", text: $phoneNumber)
                        .onChange(of: phoneNumber) { newValue in
                            print("phoneNumber: \(newValue)")
                        }
                }
                .frame(maxWidth: .infinity)
                .frame(height: 50)
                .overlay(
                    RoundedRectangle(cornerRadius: 12.0)
                        .stroke(Color.black, lineWidth: 2.0)
                )
                
                Spacer()
                    .frame(height: 10)
                
                HStack {
                    if isCountdown {
                        // 倒计时显示
                        Text("\(countdownSeconds)s")
                            .foregroundColor(.gray)
                            .frame(width: 60, alignment: .trailing)
                    } else {
                        // 获取验证码按钮
                        Button("Verification code") {
                            startCountdown()
                        }
                        .foregroundColor(.blue)
                        .overlay(
                            Rectangle()
                                .frame(height: 1)
                                .foregroundColor(.blue)
                                .offset(y: 10)
                        )
                    }
                }
                .frame(maxWidth: .infinity, alignment: .trailing)
                .frame(height: 30)
                
                Spacer()
                    .frame(height: 50)
                
                Text("Mobile verification code")
                    .frame(maxWidth: .infinity, alignment: .leading)
                    .foregroundColor(Color.black)
                
                TextField("Please enter", text: $password)
                    .frame(maxWidth: .infinity)
                    .frame(height: 50)
                    .overlay(
                        RoundedRectangle(cornerRadius: 12.0)
                            .stroke(Color.black, lineWidth: 2.0)
                    )
                    .onChange(of: password) { newValue in
                        print("password: \(newValue)")
                    }
                
                Spacer()
                    .frame(height: 30)
                
                Button("登录成功") {
                    if isPresented {
                        presentationMode.wrappedValue.dismiss()
                        SMLoginInfo.shared.logSuccess()
                    } else {
                        
                        appState.rootView = .main
                        SMLoginInfo.shared.logSuccess()
                    }
                }
                .foregroundColor(Color.black)
                
                Spacer()
            }
            .padding(.horizontal, 60)
        }
        .background(
            Image("login_bg_image")
                .resizable()
                .scaledToFill()
                .ignoresSafeArea()
        )
        .edgesIgnoringSafeArea(.all)
        .ignoresSafeArea(.keyboard, edges: .bottom)
        .onDisappear {
            // 页面消失时停止计时器
            countdownTimer?.invalidate()
            countdownTimer = nil
        }
    }
    
    private func startCountdown() {
        let phone = phoneNumber.trimmingCharacters(in: .whitespaces)
        guard phone.isEmpty else {
            return
        }
        
        // 这里可以添加发送验证码的逻辑
        print("发送验证码到: \(phoneNumber)")
        
        // 开始倒计时
        isCountdown = true
        countdownSeconds = 60
        
        countdownTimer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { timer in
            if countdownSeconds > 1 {
                countdownSeconds -= 1
            } else {
                // 倒计时结束
                stopCountdown()
            }
        }
    }
    
    private func stopCountdown() {
        countdownTimer?.invalidate()
        countdownTimer = nil
        isCountdown = false
        countdownSeconds = 60
    }
}
